package com.icesoft.system.safe.filter;

import com.icesoft.system.types.SystemSettingTypeDictionary;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RequiredArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(urlPatterns = "/*", filterName = "httpHostHeaderFilter")
public class HttpHostHeaderFilter implements Filter {

	private final SystemSettingTypeDictionary systemSettingTypeDictionary;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String serverPath = systemSettingTypeDictionary.getHost();
		if (StringUtils.isNotBlank(serverPath)) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			String host = httpServletRequest.getHeader("host").trim();
			log.trace("host:{}", host);
			if (StringUtils.isBlank(serverPath) || !serverPath.contains(host)) {
				log.warn("refuse error host access, error host={}", host);
				HttpServletResponse res = (HttpServletResponse) response;
				res.setStatus(403);
				return;
			}
		}
		chain.doFilter(request, response);
	}

}
